package com.thunder.soft.vm;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thunder.soft.bean.MyCollectBean;
import com.thunder.soft.common.base.BaseBean;
import com.thunder.soft.common.base.BaseViewModel;
import com.thunder.soft.common.net.HttpClient;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MyCollectViewModel extends BaseViewModel {
    private static final String TAG = MyCollectViewModel.class.getName();
    private MutableLiveData<MyCollectBean> myCollectLiveData = new MutableLiveData<>();

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        super.onCreate(owner);
        getMyCollect();
    }

    public void getMyCollect() {
        HttpClient.getInstance().request("lg/collect/list/0/json", "GET", null, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                getErrorMsg().postValue(e.getMessage());
                Log.d(TAG, "error");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Gson gson = new Gson();
                String string = response.body().string();
                Log.e(TAG, string);

                BaseBean<MyCollectBean> myCollectBean = gson.fromJson(string,
                        new TypeToken<BaseBean<MyCollectBean>>() {
                        }.getType());

                if (myCollectBean.getErrorCode() == 0) { //success
                    myCollectLiveData.postValue(myCollectBean.getData());
                } else {
                    getErrorMsg().postValue(myCollectBean.getErrorMsg());
                }
            }
        });
    }

    public void onBackPressed() {
        getFinishActivity().postValue(1);
    }

    public MutableLiveData<MyCollectBean> getMyCollectLiveData() {
        return myCollectLiveData;
    }
}
